/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.phoneBook.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.gadgets.client.io.AuthorizationType;
import com.google.gwt.gadgets.client.io.ContentType;
import com.google.gwt.gadgets.client.io.GadgetsIo;
import com.google.gwt.gadgets.client.io.IoProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.gadgets.client.io.RequestOptions;
import com.google.gwt.gadgets.client.io.Response;
import com.google.gwt.gadgets.client.io.ResponseReceivedHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;

public class GoogleContacts {
	
    public  static ArrayList <JSONObject> contactsList  = new ArrayList <JSONObject>() ;
    public  static boolean inProcess = false;
	static boolean callFeed(){
		
		  if(contactsList.size()>0 || inProcess )
			  return false;
		  
		  inProcess  = true;
		  //contactsList.clear();
		  
		  String url = "http://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=10000";
		  final RequestOptions options = RequestOptions.newInstance();
		  options.setAuthorizationType(AuthorizationType.OAUTH);
		  options.setContentType(ContentType.JSON);
		  options.setMethodType(MethodType.GET);
		  			
			GadgetsIo  gIO = IoProvider.get();
			
			gIO.makeRequestAsJso(url, new ResponseReceivedHandler<JsArray<JavaScriptObject>>() {
		        @Override
				public void onResponseReceived(
		                ResponseReceivedEvent<JsArray<JavaScriptObject>> event) {
		              Response<JsArray<JavaScriptObject>> response = event.getResponse();
		              if (response!=null && response.getData()!=null){
		            	 parseJson( response.getData());
		            	 inProcess = false; 	 
		              }
		                	
		              else if (response!=null && response.getOauthError()!=null){
		            	  // ignore errors .....
		            	           	 		            	 	                  
		            
		              }
		            }
		          },options);
			return true;
			}
	
	
	protected static void parseJson(JsArray<JavaScriptObject> data) {
		
		JSONArray entryArray = null;
		JSONObject entry = null;
				 
		try 
		{
		  entryArray = (new JSONObject(data)).get("feed").isObject().get("entry").isArray();
		}
		catch (Exception e) 
		{
			
		}
			
		 for(int i=0;i<entryArray.size();i++)
		 {
			 try 
			 {
				// check for name, if name valid then add
				 entry = entryArray.get(i).isObject();
				 if(entry.get("title")!=null && !entry.get("title").isObject().get("$t").isString().stringValue().isEmpty())
						 contactsList.add(entry); 
			 }
			 catch (Exception e) 
			 {
				 // don't add
			 } 
		}
	
		 Collections.sort(contactsList, new CompareByFname());
		 
	}
	// fix json "title" format to "SecondName middleName, FirstName"
	
	public static String fixNameFormat(String title){
		
		// formated!
		if (title.indexOf(",")>0 )
			return title;
		
		try {
			if (title.indexOf(" ")>0  && title.indexOf(" ") < title.length()-1)
				return title.substring(title.lastIndexOf(" ")+1)+", "+title.substring(0,title.lastIndexOf(" "));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		
		return title;
		}
	// return 
}




//  a Comparator class used to sort the contacts by Family name
class CompareByFname implements Comparator <JSONObject>{

	@Override
	public int compare(JSONObject entry1, JSONObject entry2) {
	
		String fname1 = null;
		String fname2 = null;
		try {
			fname1 = GoogleContacts.fixNameFormat(entry1.get("title").isObject().get("$t").isString().stringValue());
			fname2 = GoogleContacts.fixNameFormat(entry2.get("title").isObject().get("$t").isString().stringValue());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		if(fname1 != null && fname2 != null)
			return fname1.compareToIgnoreCase(fname2);
		else 
			return 0;
	}
	

	
}


